package com.wl.index.Biz.Impl;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.TimeZone;

@Service
public class PaymentBizImpl {
    @Value("${alipay.app-id}")
    private String appId;

    @Value("${alipay.merchant-private-key}")
    private String merchantPrivateKey;

    @Value("${alipay.alipay-public-key}")
    private String alipayPublicKey;

    @Value("${alipay.gateway-url}")
    private String gatewayUrl;

    @PostConstruct
    public void init() {
        try {
            Config config = new Config();
            config.protocol = "https";
            config.gatewayHost = "openapi.alipaydev.com";
            config.signType = "RSA2";
            config.appId = this.appId;

            // 保持密钥完整格式
            config.merchantPrivateKey = this.merchantPrivateKey;
            config.alipayPublicKey = this.alipayPublicKey;

            System.out.println("Private Key:\n" + config.merchantPrivateKey);
            System.out.println("Public Key:\n" + config.alipayPublicKey);

            // 设置时区
            TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));

            Factory.setOptions(config);
            System.out.println("支付宝SDK初始化成功");
        } catch (Exception e) {
            System.out.println("支付宝SDK初始化失败");
            throw new RuntimeException("支付宝初始化失败", e);
        }
    }

    @PostConstruct
    public void initTimeZone() {
        TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
        System.setProperty("user.timezone", "Asia/Shanghai");
    }

    public String createOrder(String outTradeNo, String subject, BigDecimal totalAmount, String returnUrl) throws Exception {
        // 参数校验
        if (StringUtils.isBlank(outTradeNo) || StringUtils.isBlank(subject) || totalAmount == null) {
            throw new IllegalArgumentException("支付参数不完整");
        }

        if (totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("支付金额必须大于0");
        }

        // 增加重试机制
        int retryCount = 0;
        Exception lastException = null;



        while (retryCount < 3) {
            try {
                AlipayTradePagePayResponse response = Factory.Payment.Page()
                        .pay(subject, outTradeNo, totalAmount.toString(), returnUrl);

                if (response == null || response.getBody() == null) {
                    throw new RuntimeException("支付宝接口返回异常");
                }

                return response.getBody();
            } catch (Exception e) {
                lastException = e;
                retryCount++;
                if (retryCount < 3) {
                    Thread.sleep(1000); // 等待1秒后重试
                }
            }
        }

        throw new RuntimeException("支付宝接口调用失败，重试3次后仍然失败", lastException);

    }

    public boolean checkPaymentStatus(String outTradeNo) throws Exception {
        // 查询支付状态
        return Factory.Payment.Common().query(outTradeNo).tradeStatus.equals("TRADE_SUCCESS");
    }
}